<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button id="add">+</button>
    <span id="box">0</span>
    <button id="lessen">-</button>

    <script src="./thunk.js"></script>
    <script src="./loger.js"></script>
    <script src="./myRedux.js"></script>
    <script>
        // action逻辑处理函数(中间件)
        function enhancer(createStore) {
            return function (reduce, preloadState) {
                const store = createStore(reduce, preloadState)
                let dispatch = store.dispatch

                function _dispatch(action) {
                    if (typeof action === "function") {
                        // action(dispatch)
                        return action(dispatch)
                    }
                    dispatch(action)
                }

                return {
                    ...store,
                    dispatch: _dispatch
                }
            }
        }


        function counterReduce(state, action) {
            console.log(state)
            switch (action.type) {
                case "add":
                    return state + 1
                case "lessen":
                    return state - 1
                default:
                    return state
            }
        }

        const rootReduce = combineReducers({ count: counterReduce })

        // 创建store
        const store = createStore(rootReduce, { count: 0 }, applymiddleware(loger, thunk))
        // 用bindActionCreatetors接受action
        const actions = bindActionCreatetors({ add, lessen }, store.dispatch)

        function add() {
            return { type: "add" }
        }

        function lessen() {
            return { type: "lessen" }
        }

        let addbuton = document.getElementById("add")
        let box = document.getElementById("box")
        let lessenbuton = document.getElementById("lessen")

        // 触发添加action
        addbuton.onclick = function () {
            store.dispatch((dispatch) => {
                setTimeout(() => {
                    actions.add()
                }, 1000)
            })
        }
        // 触发减少action
        lessenbuton.onclick = function () {
            actions.lessen()
        }

        // 获取最新的store状态
        store.subscribe(() => {
            console.log(store.getState())
            box.innerHTML = store.getState().count
        })

    </script>
</body>

</html>